import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import QueueAnim from 'rc-queue-anim';
import TweenOne from 'rc-tween-one';
import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, } from 'antd';
import BaseComponent from '@/components/BaseComponent';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import StandardTableHandle from '@/components/StandardTable/StandardTableHandle';
import { questions as columns } from '@/commons/columns';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, queryRow = {}, form, handleUpdate, handleModalVisible } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleUpdate(Object.assign({}, fieldsValue, queryRow.id ? { method: 'PUT', id: queryRow.id } : { method: 'POST' }));
    });
  };

  return (
    <Modal
      destroyOnClose
      width={500}
      title={queryRow.id ? '编辑常见问题' : '新增常见问题'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={handleModalVisible.bind(null)}
    >
      <FormItem labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} label="问题标题">
        {form.getFieldDecorator('title', {
          initialValue: queryRow.title,
          rules: [{ message: '请输入8～32个字符间的问题标题！', min: 8, max: 32 }],
        })(<Input placeholder="请输入问题标题" />)}
      </FormItem>
      <FormItem labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} label="问题简述" style={{marginBottom: 0}}>
        {form.getFieldDecorator('brief', {
          initialValue: queryRow.brief,
          rules: [{ message: '请输入16～200个字符间的问题简述！', min: 16, max: 200 }],
        })(<TextArea placeholder="请输入问题简述" autosize={{ minRows: 5, maxRows: 6 }} />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ questions, loading }) => ({
  questions,
  loading: loading.models.questions,
}))
@Form.create()
class TableList extends BaseComponent {
  constructor(props) {
    super(props);
    this.namespace = 'questions';
    this.title = '常见问题';
    this.state = {
      modalVisible: false,
      selectedRows: [],
      formValues: {},
      queryRow: {},
    };
  }

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: queryRow => (
      <Button icon="edit" ghost type="primary" size="small" onClick={this.handleModalVisible.bind(null, queryRow)}>编辑</Button>
    ),
  }];

  handleModalVisible = (queryRow = {}) => {
    const payload = { queryRow };

    if (isNaN(queryRow.id)) {
      Object.assign(payload, {
        modalVisible: false,
      });
    } else {
      Object.assign(payload, {
        modalVisible: true,
      });
    };

    this.setState(state => ({
      ...state,
      ...payload
    }));
  };

  handleUpdate = payload => {
    const { dispatch } = this.props;

    switch (payload.method) {
      case 'PUT':
        delete payload.method;
        dispatch({
          type: 'questions/update',
          payload,
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('常见问题更新失败！');
            } else {
              dispatch({
                type: 'questions/fetch',
              });

              message.success(`序号${payload.id}的常见问题更新成功～`);

              this.handleModalVisible();
            }
          }
        });
        break;
      case 'POST':
        delete payload.method;
        dispatch({
          type: 'questions/add',
          payload,
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('常见问题新增失败！');
            } else {
              dispatch({
                type: 'questions/fetch',
              });

              message.success(`序号${data.id}的常见问题新增成功～`);

              this.handleModalVisible();
            }
          }
        });
        break;
      default:
        message.error('不太清楚你在搞什么破坏');
        break;
    }
  };

  render() {
    const {
      questions: { data, status },
      loading,
    } = this.props;
    const { queryRow, selectedRows, modalVisible } = this.state;

    const parentMethods = {
      queryRow,
      handleUpdate: this.handleUpdate,
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <PageHeaderWrapper 
        title={this.title} 
        action={moment().format('LLLL')}
      >
        <Card bordered={false}>
          <StandardTableHandle
            status={status}
            selectedRows={selectedRows}
            menuItems={{'remove': <Button type="danger" icon="delete">删除</Button>}}
            action={
              <Button type="primary" icon="plus" onClick={this.handleModalVisible.bind(null, {id: 0})}>新增</Button>
            }
            onToggleTable={this.handleGroupChange}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            scroll={{ x: 1300 }}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleTableChange}
          />
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;